//
//  ApplyMemberViewController.m
//  YuanCheng
//
//  Created by 朱亚杰 on 16/4/6.
//  Copyright © 2016年 dongshangtong. All rights reserved.
//
#define kCellHeight 44
#define kPictureHeight 150

#import "ApplyMemberViewController.h"
#import "UseAgreementViewController.h"
#import "RegKnownViewController.h"
#import "YCTabbarViewController.h"
#import "YCNavViewController.h"
#import "MembershipViewController.h"
//#import "PositionViewController.h"
//#import "HospitalLevel.h"
#import "SelectHosNameViewController.h"
#import "HosNameListModel.h"
#import "NSString+Size.h"
#import "UIViewController+YCExtension.h"

#define kDOC_name 0
#define kDOC_sex 1
#define kDOC_birth 2

#define kDOC_hospital 3
#define kDOC_department 4
#define kDOC_duty 5
#define kDOC_certificate 6
#define kDOC_phone 7

#define kDOC_iconPicture 8
#define kDOC_professionPicture 9
#define kDOC_jobPicture 10
#define kDOC_signaturePicture 11

#define kDOC_referrer 12

#define kControlH 15

@interface ApplyMemberViewController () <UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    CGFloat _maxScrollViewHeight;
    UIImageView *uploadImgView;
}

@property (copy, nonatomic) NSString *applyStr;

@property (weak, nonatomic) IBOutlet UIView *tabView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;


@property(nonatomic, weak) UITextField *docNameTextField;
@property(nonatomic, weak) UITextField *docSexTextField;
@property(nonatomic, weak) UITextField *docBirthTextFied;

@property(nonatomic, weak) UITextField *docHospitalTextField;
@property(nonatomic, weak) UIButton *docHospitalButton;
@property(nonatomic, weak) UITextField *docDepartmentTextField;
@property(nonatomic, weak) UITextField *docDutyTextField;
@property(nonatomic, weak) UITextField *docCertificateTextField;
@property(nonatomic, weak) UITextField *docPhoneTextField;

@property(nonatomic, strong) UIImageView *uploadImageView;
@property(nonatomic, strong) UIImageView *iconImageView;
@property(nonatomic, strong) UIImageView *professionImageView;
@property(nonatomic, strong) UIImageView *jobImageView;
@property(nonatomic, strong) UIImageView *signatureImageView;

@property(nonatomic, weak) UITextField *docReferrerTextField;

@property(nonatomic, strong) UIToolbar *topToolBar;
@property(nonatomic, strong) NSArray *levelArr;

@end

@implementation ApplyMemberViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.hidden = NO;
    [self setupViews];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)dealloc {
    [self clearKeyboardCorverNotificationAndGesture];
}

- (void)setupViews {
    
    //    1.设置背景颜色
    _tabView.backgroundColor = GreenColor;
    _scrollView.backgroundColor = BackgroundColor;

    
    //    3. 注册信息
    UILabel *regTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, MarginWidth, MaxViewWidth, 24)];
    regTitle.font = SubTitleFont;
    regTitle.textAlignment = NSTextAlignmentCenter;
    regTitle.text = @"身份认证";
    regTitle.textColor = [UIColor blackColor];
    [_scrollView addSubview:regTitle];
    _maxScrollViewHeight = CGRectGetMaxY(regTitle.frame);
    
    
        //   个人信息
    NSArray *baseInfo = @[
                          @{
                              @"name":@"姓名",
                              @"tag":@(kDOC_name),
                              @"necessary":@"1"
                              },
                          @{
                              @"name":@"性别",
                              @"tag":@(kDOC_sex),
                              @"necessary":@"1"
                              },
                          @{
                              @"name":@"出生年月",
                              @"tag":@(kDOC_birth),
                              @"necessary":@"0"
                              }
                          ];
    [self addSubViews:baseInfo andPicture:0];
    
    //    职位信息
    NSArray *contactInfo = @[
                             @{
                                 @"name":@"医院",
                                 @"tag":@(kDOC_hospital),
                                 @"necessary":@"1"
                                 },
                             @{
                                 @"name":@"科室",
                                 @"tag":@(kDOC_department),
                                 @"necessary":@"1"
                                 },
                             @{
                                 @"name":@"职务职称",
                                 @"tag":@(kDOC_duty),
                                 @"necessary":@"1"
                                 },
                             @{
                                 @"name":@"医生从业资格证",
                                 @"tag":@(kDOC_certificate),
                                 @"necessary":@"1"
                                 },
                             @{
                                 @"name":@"手机号",
                                 @"tag":@(kDOC_phone),
                                 @"necessary":@"1"
                                 }
                             ];
    [self addSubViews:contactInfo andPicture:0];
    
    //    证书信息
    NSArray *pictureInfo = @[
                             @{
                                 @"name":@"医生照片",
                                 @"tag":@(kDOC_iconPicture),
                                 @"necessary":@"0"
                                 },
                             @{
                                 @"name":@"医师职业证书照片",
                                 @"tag":@(kDOC_professionPicture),
                                 @"necessary":@"0"
                                 },
                             @{
                                 @"name":@"工作证照片",
                                 @"tag":@(kDOC_jobPicture),
                                 @"necessary":@"0"
                                 },
                             @{
                                 @"name":@"医生签名照片",
                                 @"tag":@(kDOC_signaturePicture),
                                 @"necessary":@"1"
                                 }
                             ];
    [self addSubViews:pictureInfo andPicture:1];
    
    //推荐人电话
    NSArray * referrerInfo = @[
                               @{
                                   @"name":@"推荐人电话",
                                   @"tag":@(kDOC_referrer),
                                   @"necessary":@"0"
                                   }
                               ];
    [self addSubViews:referrerInfo andPicture:0];
    
    //    4.同意协议和须知
    
    CGFloat agreeButtonY = _maxScrollViewHeight + 30;
    CGFloat agreeButtonX = SCREEN_WIDTH * 0.2;
    CGFloat agreeButtonW = kControlH;
    CGFloat agreeButtonH = agreeButtonW;
    UIButton *agreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    agreeButton.frame = CGRectMake(agreeButtonX, agreeButtonY, agreeButtonW, agreeButtonH);
    [agreeButton setImage:[UIImage imageNamed:@"agreeImage"] forState:UIControlStateNormal];
    [_scrollView addSubview:agreeButton];
    _maxScrollViewHeight = CGRectGetMaxY(agreeButton.frame);
    
    NSString *agreeLabelText = @"同意";
    CGFloat agreeLabelY = agreeButtonY;
    CGFloat agreeLabelX = CGRectGetMaxX(agreeButton.frame) + 5;
    CGFloat agreeLabelH = kControlH;
    CGFloat agreeLabelW = [agreeLabelText sizeWithTextFont:AddressFont textMaxSize:CGSizeMake(SCREEN_WIDTH, MAXFLOAT)].width;
    UILabel *agreeLabel = [[UILabel alloc] initWithFrame:CGRectMake(agreeLabelX, agreeLabelY, agreeLabelW, agreeLabelH)];
    agreeLabel.text = agreeLabelText;
    agreeLabel.font = AddressFont;
    [_scrollView addSubview:agreeLabel];
    
    NSString *protocalButtonText = @"用户使用协议";
    CGFloat protocalButtonY = agreeButtonY;
    CGFloat protocalButtonX = CGRectGetMaxX(agreeLabel.frame);
    CGFloat protocalButtonH = kControlH;
    CGFloat protocalButtonW = [protocalButtonText sizeWithTextFont:AddressFont textMaxSize:CGSizeMake(SCREEN_WIDTH, MAXFLOAT)].width;
    UIButton *protocalButton = [UIButton buttonWithType:UIButtonTypeCustom];
    protocalButton.frame = CGRectMake(protocalButtonX, protocalButtonY, protocalButtonW, protocalButtonH);
    [protocalButton setTitle:protocalButtonText forState:UIControlStateNormal];
    protocalButton.titleLabel.font = AddressFont;
    [protocalButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
     [protocalButton addTarget:self action:@selector(protocalClick) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:protocalButton];
    
    NSString *andLabelText = @"和";
    CGFloat andLabelY = agreeButtonY;
    CGFloat andLabelX = CGRectGetMaxX(protocalButton.frame);
    CGFloat andLabelW = kControlH;
    CGFloat andLabelH = [andLabelText sizeWithTextFont:AddressFont textMaxSize:CGSizeMake(SCREEN_WIDTH, MAXFLOAT)].width;
    UILabel *andLabel = [[UILabel alloc] initWithFrame:CGRectMake(andLabelX, andLabelY, andLabelW, andLabelH)];
    andLabel.font = AddressFont;
    andLabel.text = andLabelText;
    [_scrollView addSubview:andLabel];
    
    NSString *noticeButtonText = @"注册须知";
    CGFloat noticeButtonY = agreeButtonY;
    CGFloat noticeButtonX = CGRectGetMaxX(andLabel.frame);
    CGFloat noticeButtonH = kControlH;
    CGFloat noticeButtonW = [noticeButtonText sizeWithTextFont:AddressFont textMaxSize:CGSizeMake(SCREEN_WIDTH, MAXFLOAT)].width;
    UIButton *noticeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    noticeButton.frame = CGRectMake(noticeButtonX, noticeButtonY, noticeButtonW, noticeButtonH);
    noticeButton.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [noticeButton setTitle:noticeButtonText forState:UIControlStateNormal];
    [noticeButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [_scrollView addSubview:noticeButton];
    
    [noticeButton addTarget:self action:@selector(lookRegKnown) forControlEvents:UIControlEventTouchUpInside];
    
    
    //    5.提交申请表，查看注册须知按钮
    CGFloat sumbmitBtnY = _maxScrollViewHeight + 25;
    UIButton *sumbmitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat buttonWidth = (SCREEN_WIDTH - 60);
    sumbmitBtn.frame = CGRectMake((SCREEN_WIDTH - buttonWidth)/2, sumbmitBtnY, buttonWidth, 40);
    [sumbmitBtn setTitle:@"提交申请表" forState:UIControlStateNormal];
    [sumbmitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sumbmitBtn setBackgroundColor:GreenColor];
    [sumbmitBtn addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:sumbmitBtn];
    
    _maxScrollViewHeight = CGRectGetMaxY(sumbmitBtn.frame) + 80;
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, _maxScrollViewHeight);
    
    [self addKeyboardCorverNotification];
}

//MARK: - BottomAgreeViewDelegate

- (void)jumpToRegisterNotice{
    [self lookRegKnown];
}

#pragma mark - 添加子类视图
- (void)addSubViews:(NSArray *)array andPicture:(NSInteger)isPicture{
    
    //设置父类视图
    CGFloat viewY = _maxScrollViewHeight + 10;
    CGFloat viewHeight = array.count * kCellHeight - 1;
    CGFloat leftMargin = 5;
    if (isPicture) {
        viewHeight = array.count * kPictureHeight;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(leftMargin, viewY, SCREEN_WIDTH - leftMargin, viewHeight)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 5;
    view.clipsToBounds = YES;
    [_scrollView addSubview:view];
    _maxScrollViewHeight = CGRectGetMaxY(view.frame);
    
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //1.设置属性名
        NSInteger idxInt = (NSInteger)idx;
        CGFloat labelX = MarginWidth;
        CGFloat labelY = idxInt * (kCellHeight + 1);
        NSString *name = obj[@"name"];
        CGSize nameSize = [name sizeWithTextFont:SubTitleFont textMaxSize:CGSizeMake(SCREEN_WIDTH, MAXFLOAT)];
        CGFloat labelWidth = nameSize.width;
        if (isPicture) {
            labelY = idxInt * (kPictureHeight + 1);
        }
        UILabel *label = [[UILabel alloc] init];
        label.frame = CGRectMake(labelX, labelY, labelWidth, kCellHeight);
        label.text = obj[@"name"];
        label.font = SubTitleFont;
        label.textColor = [UIColor blackColor];
        [view addSubview:label];
        
        //2.设置是否必填的图片
        if ([obj[@"necessary"] isEqualToString:@"1"]) {
            CGFloat imageViewX = label.x + label.width;
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageViewX, (labelY + 18), 6, 6)];
            imageView.image = [UIImage imageNamed:@"icon_need"];
            [view addSubview:imageView];
        }
        
        //3.设置输入框
        NSInteger tag = [obj[@"tag"] integerValue];
        CGFloat textX = SCREEN_WIDTH/2;
        CGFloat textWidth = MaxViewWidth - textX - MarginWidth;
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(textX, labelY, textWidth, kCellHeight)];
        textField.keyboardType =UIReturnKeyDone;
        textField.placeholder = obj[@"name"];
        textField.delegate = self;
        textField.font = LevelFont;
        textField.textAlignment = NSTextAlignmentLeft;
        textField.textColor = Gray;
        [textField setReturnKeyType:UIReturnKeyDone];
        [textField setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        
        if (tag == kDOC_name) {                 //医生姓名
            _docNameTextField = textField;
            [view addSubview:textField];
        }else if (tag == kDOC_sex){             //医生性别
            _docSexTextField = textField;
            [view addSubview:textField];
        }else if (tag == kDOC_birth){           //医生出生日期
            _docBirthTextFied = textField;
            [view addSubview:textField];
            //弹出日期选择框
            [self popDatePickerView];
            
        }else if (tag == kDOC_hospital){        //医生所在医院
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            CGFloat buttonX = textX;
            CGFloat buttonWidth = textWidth;
            button.frame = CGRectMake(buttonX, (labelY+8), buttonWidth, 28);
            button.titleLabel.font = LevelFont;
            button.titleLabel.textAlignment = NSTextAlignmentCenter;
            button.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
            [button setTitle:@"选择医院" forState:UIControlStateNormal];
            [button setTitleColor:Gray forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"down_ arrow"] forState:UIControlStateNormal];
            [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 38)];
            [button setImageEdgeInsets:UIEdgeInsetsMake(0, (buttonWidth - 38), 0, 0)];
            [button addTarget:self action:@selector(hosSelect:) forControlEvents:UIControlEventTouchUpInside];
            button.layer.cornerRadius = 3;
            button.clipsToBounds = YES;
            button.layer.borderWidth = 1;
            button.layer.borderColor = GrayBorderColor.CGColor;
            [view addSubview:button];
            _docHospitalButton = button;
            
        }else if (tag == kDOC_department){      //医生科室
            _docDepartmentTextField = textField;
            [view addSubview:textField];
        }else if (tag ==kDOC_duty){             //医生职称
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(textX, labelY, textWidth, kCellHeight)];
            textField.placeholder = @"";
            textField.font = LevelFont;
            textField.textAlignment = NSTextAlignmentLeft;
            textField.textColor = Gray;
            [view addSubview:textField];
            _docDutyTextField = textField;
            
            UIPickerView *pickerView = [[UIPickerView alloc] init];
            pickerView.dataSource = self;
            pickerView.delegate = self;
            _docDutyTextField.inputView = pickerView;
            _docDutyTextField.inputAccessoryView = self.topToolBar;
            _docDutyTextField.text = @"住院医师";
            
        }else if (tag == kDOC_certificate){     //医生从业资格证
            _docCertificateTextField = textField;
            
            [_docCertificateTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

            _docCertificateTextField.placeholder = @"从业资格证编码";
            [view addSubview:textField];
        }else if (tag == kDOC_phone){           //医生手机号
            _docPhoneTextField = textField;
            _docPhoneTextField.userInteractionEnabled = NO;
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            _docPhoneTextField.text = [def objectForKey:KLINKMOBILE];
            _docPhoneTextField.placeholder = @"保持和注册号一致";
            [view addSubview:textField];
        }else if (tag == kDOC_referrer){        //推荐人
            _docReferrerTextField = textField;
            [view addSubview:textField];
        }

        //  4.判断是否添加图片
        if (!isPicture) {
            if (idxInt != array.count) {
                CGFloat dividerY = idxInt * kCellHeight;
                UIView *divider = [[UIView alloc] initWithFrame:CGRectMake(0, dividerY, MaxViewWidth, 1)];
                divider.backgroundColor = DividerColor;
                [view addSubview:divider];
            }
        }else{
            CGFloat dividerY = idxInt * kPictureHeight + kCellHeight;
            UIView *divider = [[UIView alloc] initWithFrame:CGRectMake(0, dividerY, MaxViewWidth, 1)];
            divider.backgroundColor = DividerColor;
            [view addSubview:divider];
            
            uploadImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"uploadImage"]];
            uploadImgView.userInteractionEnabled = YES;
            CGFloat uploadImgViewWidth = 60;
            CGFloat uploadImgViewX = (SCREEN_WIDTH - uploadImgViewWidth)/2;
            CGFloat uploadImgViewY = (kCellHeight + 20) + idxInt * kPictureHeight;
            uploadImgView.frame = CGRectMake(uploadImgViewX, uploadImgViewY, uploadImgViewWidth, uploadImgViewWidth);
            uploadImgView.backgroundColor = LigthGray;
            [view addSubview:uploadImgView];
            [uploadImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uploadImageTapGesture:)]];
            
            if (tag == kDOC_iconPicture) {
                self.iconImageView = uploadImgView;
            }else if (tag == kDOC_professionPicture){
                self.professionImageView = uploadImgView;
            }else if (tag == kDOC_jobPicture){
                self.jobImageView = uploadImgView;
            }else if (tag == kDOC_signaturePicture){
                self.signatureImageView = uploadImgView;
            }
            
        }
    }];
    
}

//MARK: - 日期选择框
- (void)popDatePickerView{
    //      设置弹出键盘
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.datePickerMode = UIDatePickerModeDate;
    //      设置日期为30年前
    NSDate *mydate = [NSDate date];
    NSCalendar *calendar1 = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar1 components:NSCalendarUnitYear fromDate:mydate];
    NSInteger year = [dateComponent year] - 30;
    NSString *str = [NSString stringWithFormat:@"%ld-01-01", year];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    mydate = [fmt dateFromString:str];
    [datePicker setDate:mydate];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *currentDate = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:0];//设置最大时间为：当前时间推后十年
    NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
    [comps setYear:-100];//设置最小时间为：当前时间前推十年
    NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
    //
    [datePicker setMaximumDate:maxDate];
    [datePicker setMinimumDate:minDate];
    //                [datePicker setDate:currentDate];
    
    
    datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [datePicker addTarget:self action:@selector(birthdayChanged:) forControlEvents:UIControlEventValueChanged];
    _docBirthTextFied.inputView = datePicker;
    _docBirthTextFied.inputAccessoryView = self.topToolBar;
    _docBirthTextFied.placeholder=@"年-月-日";
}

#pragma mark - 选择照片

- (void)uploadImageTapGesture:(UITapGestureRecognizer *)recognizer{
    //        上传头像
    self.uploadImageView = (UIImageView *)recognizer.view;
    
    UIAlertController  *alView = [UIAlertController alertControllerWithTitle:@"请从选择相机或相册" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alView addAction: [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self opnenCamereAndPhotoLibrary:UIImagePickerControllerSourceTypeCamera];
    }]];
    
    
    [alView addAction: [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self opnenCamereAndPhotoLibrary:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    }]];
    
    [alView addAction: [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    
    [self presentViewController:alView animated:YES completion:^{
        
    }];
}

#pragma mark 打开相机，相册，图库
-(void)opnenCamereAndPhotoLibrary:(UIImagePickerControllerSourceType )type {
    
    UIImagePickerController *impk;
    //    相机
    if (type ==UIImagePickerControllerSourceTypeCamera) {
        
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
        
        impk = [[UIImagePickerController alloc]init];
        impk.sourceType=type;
        impk.delegate= self;
        impk.allowsEditing = YES;
        [self presentViewController:impk animated:YES completion:^{
            [self updataProfileData:@"delegate"];
        }];
        
        //        相册
    }else if(type ==UIImagePickerControllerSourceTypeSavedPhotosAlbum){
        
        impk= [[UIImagePickerController alloc]init];
        impk.delegate= self;
        impk.allowsEditing = YES;
        impk.sourceType=type;
        [self presentViewController:impk animated:YES completion:^{
            
        }];
        
    }
}

#pragma mark - imagePickerController 代理方法

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.uploadImageView.image = image;
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

// 跟新本地数据
- (void)updataProfileData:(NSString *)str {
    //判断token 是否过期
    if (![YCCommonTool tokenExistAndAccess_tokenExpire]) {
        
        [DownloadData getAccess_token];
    }
   
}

// 取消选择图片
-(void)imagePickerControllerDIdCancel:(UIImagePickerController*)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 生日文本框日期
-(void)birthdayChanged:(UIDatePicker *)datePicker{
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    dateFormat.dateFormat = @"yyyy-MM-dd";
    _docBirthTextFied.text = [dateFormat stringFromDate:datePicker.date];
    
}

#pragma mark 点击选择医院
-(void)hosSelect:(UIButton *)btn {
    
    SelectHosNameViewController *hoslistVC = [[SelectHosNameViewController alloc]init];
    hoslistVC.flag =@"1";
    YCNavViewController *nav = [[YCNavViewController alloc]initWithRootViewController:hoslistVC];
    hoslistVC.hosListName = ^(HosNameListModel *hos){
        
        [_docHospitalButton setTitle:hos.hosName forState:UIControlStateNormal];
    };
    
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - 职务职称弹出pickerView
#pragma mark 返回列数（总共有多少列）
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 1;
}
#pragma mark 返回行数 第compnent列总共有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    return self.levelArr.count;
}
#pragma mark 返回第component列第row行的显示内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    return self.levelArr[row];
}
#pragma mark 选中某一行的操作
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    _docDutyTextField.text = self.levelArr[row];
}

#pragma mark - 生日文本框的代理
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == _docBirthTextFied || textField == _docDutyTextField) {
        return NO;
    }else{
        return YES;
    }
}

-(void)textFieldDidChange:(UITextField *)textField{
    
    if (![NSString yc_isNumOrLetter:self.docCertificateTextField.text]) {
        [self presentFailureTips:@"医生就业资格证只能输入数字和字母"];
        return;
    }
    
    NSString *text = textField.text;
    
    NSUInteger asciiLength = 0;
    
    for (NSUInteger i = 0; i < text.length; i++) {
        
        unichar uc = [text characterAtIndex: i];
        
        asciiLength += isascii(uc) ? 1 : 2;
        
        if (asciiLength > 50) {
            
            textField.text = [textField.text substringToIndex:i];
            [self presentMessageTips:@"您输入的长度超过限制"];
            return;
        }
    }

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    [textField endEditing:YES];
    return YES;
}


//键盘退下啊
-(void)resignKeyboard{
    
    
    [self.view endEditing:YES];

    
}
//键盘退下啊

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    [self.view endEditing:YES];
    
}

//检查用户是否填写信息完了
-(BOOL)checkInformation {
 

    if (_docNameTextField.text.length == 0) {
        [self presentFailureTips:@"医生名字没有填写"];
        return NO;
    }
    if (_docSexTextField.text.length == 0) {
        [self presentFailureTips:@"医生性别没有填写"];
        return NO;
    }
    if (!([_docSexTextField.text isEqualToString:@"男"] || [_docSexTextField.text isEqualToString:@"女"])) {
        [self presentFailureTips:@"请填写正确格式的性别：‘男’或‘女’"];
        return NO;
    }
    
    if (self.docHospitalButton.currentTitle.length == 0 || [self.docHospitalButton.currentTitle isEqualToString:@"选择医院"]) {
        [self presentFailureTips:@"医院没有填写"];
        return NO;
    }
    if (self.docDepartmentTextField.text.length == 0) {
        [self presentFailureTips:@"科室没有填写"];
        return NO;
    }
    if (self.docDutyTextField.text.length == 0) {
        [self presentFailureTips:@"职务职称没有填写"];
        return NO;
    }
    if (self.docCertificateTextField.text.length == 0) {
        [self presentFailureTips:@"从业资格证没有填写"];
        return NO;
    }
    
    if (![NSString yc_isNumOrLetter:self.docCertificateTextField.text]) {
        [self presentFailureTips:@"医生就业资格证只能输入数字和字母"];
        return NO;
    }

    if (self.docPhoneTextField.text.length == 0) {
        [self presentFailureTips:@"手机号没有填写"];
        return NO;
    }
    NSUserDefaults *def= [NSUserDefaults standardUserDefaults];
    NSString *phone = [def objectForKey:KLINKMOBILE];
    if (![phone isEqualToString:self.docPhoneTextField.text]) {
        [self presentFailureTips:@"手机号与注册号码不一样"];
        return NO;
    }
    
    
    if (!self.signatureImageView.image || [self.signatureImageView.image isEqual:[UIImage imageNamed:@"uploadImage"]]) {
        [self presentFailureTips:@"医生签名照片没有添加"];
        return NO;
    }
    
    
    return YES;
}

#pragma mark - 提交申请表 按钮事件
- (void)submit {
    
    if (![self checkInformation]) return;
    [self presentLoadingTips:nil];
    NSString *expertId = [[NSUserDefaults standardUserDefaults] objectForKey:KEXPERTID];
    NSString *url = kdocInfoAdd1Url;
//    NSString *url =[YCUrlManager sharedInstance].docInfoAdd1Url;
    
    NSString *smallImage = [YCCommonTool base64ImageData:self.iconImageView.image];
    NSString *certificateidImage = [YCCommonTool base64ImageData:self.professionImageView.image];
    NSString *workImage =  [YCCommonTool base64ImageData:self.jobImageView.image];
    NSString *signatureImage = [YCCommonTool base64ImageData:self.signatureImageView.image];
    NSString *sex = @"";
    if ([_docSexTextField.text isEqualToString:@"男"]) {
        sex = @"0";
    }
    if ([_docSexTextField.text isEqualToString:@"女"]) {
        sex = @"1";
    }
    
    NSDictionary *param = @{
                            @"expert_id":expertId,//@"484239"
                            @"yw_id":yw_id,
                            
                            @"expert_name":_docNameTextField.text,
                            @"expert_sex":sex,
                            @"birth_date":_docBirthTextFied.text,
                            
                            @"hos_name":_docHospitalButton.currentTitle,
                            @"dep_name":_docDepartmentTextField.text,
                            @"expert_role":_docDutyTextField.text,
                            @"expert_certificateid":_docCertificateTextField.text,
                            @"link_mobile":_docPhoneTextField.text,
                            
                            @"small_pic":smallImage,
                            @"certificateid_pic":certificateidImage,
                            @"work_pic":workImage,
                            @"doc_signature":signatureImage,
                            
                            @"tj_mobile":_docReferrerTextField.text,
                            };
    
    
    [DownloadData post:url params:param success:^(id json) {
        [self dismissTips];
        NSString *str = json[@"error_code"];
        if ([str isEqualToString:@"ok"]){
            //保存专家的基本资料用查看状态
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            [def setObject:_docNameTextField.text forKey:KEXPERTNAME];
            [def setObject:_docPhoneTextField.text forKey:KLINKMOBILE];
            [def setObject:_docHospitalButton.currentTitle forKey:KHOSNAME];
            //改变专家审核状态
            [def setObject:@"0" forKey:KCHECKFLAG];
            [def synchronize];
            
            [[UIApplication sharedApplication].keyWindow presentSuccessTips:@"你的资料在审核中..."];
            
            MembershipViewController *memVC = [[MembershipViewController alloc]init];
            memVC.popType = self.popType;
            
            
            if (self.popType == MEMBER_SHIP_POP_TYPE_POP)
            {
                
                [self dismissViewControllerAnimated:YES completion:nil];
                
            }
            else
            {
                YCNavViewController *nav = [[YCNavViewController alloc]initWithRootViewController:memVC];
                [self presentViewController:nav animated:YES completion:nil];
                
            }
            
        }
        else
        {
            NSString *errorStr = [YCCommonTool getErrorStr:json[@"error_code"]];
            [[UIApplication sharedApplication].keyWindow presentSuccessTips:[NSString stringWithFormat:@"你提交资料失败！ - %@", errorStr]];
            
        }
        
    } failure:^(NSError *error) {
        [self dismissTips];
        
        [self presentSuccessTips:@"你提交资料失败！"];
    }];
}

#pragma mark - 将图片转成字符串
-(NSString *)UIImageToBase64Str:(UIImage *) image
{
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

#pragma mark - 查看注册须知 按钮事件
- (void)lookRegKnown {
    
    RegKnownViewController *known = [[RegKnownViewController alloc] init];
    [self presentViewController:known animated:YES completion:nil];
}


#pragma mark - 查看协议 按钮事件
-(void)protocalClick{
    
    
    UseAgreementViewController *known = [[UseAgreementViewController alloc] init];
    [self presentViewController:known animated:YES completion:nil];

    
}

#pragma mark - 点击关闭按钮
- (IBAction)backAction {
    
    [self.view endEditing:YES];
    
    if (self.popType == MEMBER_SHIP_POP_TYPE_POP)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        [self cleanPresentedVCWithCompletion:^{
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            window.rootViewController = [[YCTabbarViewController alloc] init];
        }];

    }
}

#pragma mark - lazy load

- (UIToolbar *)topToolBar{
    if (!_topToolBar) {
        _topToolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        [_topToolBar setBarStyle:UIBarStyleDefault];
        UIBarButtonItem * fixButton =[[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone  target:self action:@selector(resignKeyboard)];
        NSArray * buttonsArray = [NSArray arrayWithObjects:fixButton,doneButton,nil];
        [_topToolBar setItems:buttonsArray];
    }
    return _topToolBar;
}

- (NSArray *)levelArr{
    if (!_levelArr) {
        _levelArr = @[
                      @"住院医师",
                      @"主治医师",
                      @"副主任医师",
                      @"主任医师",
                      @"实习医生",
                      @"基层医生",
                      @"其他医师"
                      ];
    }
    return _levelArr;
}

@end
